/*
 *	Define a manager for particle system
 */
define(["core/boilerplate", "core/manager"],
	function(Boilerplate, Manager) {
		var ParticleEngine = function() {
			this.particles	= {
				alive	: [],
				dead	: []
			};

			this.time		= 0;
		}
		
		// Define prototype methods
		ParticleEngine.prototype = {
			init : function(cE, parameters) {
			},

			add : function(model) {
				var particle = new Particle(model);

				particle.time += this.time;

				this.particles.alive.push(particle);
			},

			update : function() {

				this.time ++;

				for(var i = 0, c = this.particles.alive.length; i < c; i++) {
					var particle = this.particles.alive[i];

					if(this.time > particle.time) {
						this.destroy(i);

						c --;
						continue;
					}

					particle.update();
				}

				for(var i = 0, c = this.particles.dead.length; i < c; i++) {
					var particle = this.particles.dead[i];

					if(this.time > particle.time) {
						this.particles.dead.splice(i, 1);

						c --;
						continue;
					} else {
						particle.update();						
					}
				}
			},

			render : function() {
				for(var i = 0, c = this.particles.alive.length; i < c; i++) {
					this.particles.alive[i].render();
				}

				for(var i = 0, c = this.particles.dead.length; i < c; i++) {
					this.particles.dead[i].render();
				}
			},

			resize : function() {
				for(var i = 0, c = this.particles.alive.length; i < c; i++) {
					this.particles.alive[i].resize();
				}

				for(var i = 0, c = this.particles.dead.length; i < c; i++) {
					this.particles.dead[i].resize();
				}
			},

			destroy : function(index) {

				var particle = this.particles.alive[index];

				this.particles.dead.push(particle);

				this.particles.alive.splice(index, 1);

				particle.destroy();
			}
		}

		var Particle = function(model) {
			this.position 	= model.position !== undefined ? {x:model.position.x,y:model.position.y} : {x:0,y:0};
			this.size 		= model.size !== undefined ? {x:model.size.x,y:model.size.y} : {x:0,y:0};
			this.speed 		= model.speed !== undefined ? {x:model.speed.x,y:model.speed.y} : {x:0,y:0};

			this.time 	= model.time 	|| 0;
			this.color 	= model.color 	|| "rgba(0,0,0,1)";

			this.update 	= model.update	|| function(){
				this.position.x += this.speed.x;
				this.position.y += this.speed.y;
			};
			this.render 	= model.render 	|| function(){
				ctx.fillStyle = this.color;
				ctx.fillRect(this.position.x, this.position.y, this.size.x, this.size.y);
			};

			this.resize 	= model.resize 	|| function(){};
			this.destroy	= model.destroy || function(){};

		}

		return ParticleEngine;
	}
);